﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Senparc.Weixin.MP.TenPayLibV3;
using DormMS.IService;
using DormMS.Model;
using DormMS.Model.SearchModels;
using DormMS.Model.ViewModels;
using Infrastructure;
using DormMS.Model.Enum;
using DormMS.Model.SearchModels.Activity;
using System.Net;
using System.Text;
using System.IO;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Xml.Linq;

namespace DormMS.Controllers
{
    public class ActivityController : BaseController
    {
        protected ISpecialTopicService specialtopicservice;
        protected IProductCategoryService categoryservice;
        protected IProductService productservice;
        protected ISpikeService spikeservice;
        protected IActivityService activityservice;
        protected IDrawService drawservice;
        protected IActivityTeam activityteam;
        private IWxConfigService configService;
        private IActivityTeamMembersService activityteammembersservice;
        private IActivityRuleService activityruleservice;
        public ActivityController(IUserInfoService s, ISpecialTopicService _specialtopicservice, IProductCategoryService _categoryservice, IProductService _productservice, ISpikeService _spikeservice, IActivityService _activityservice, IDrawService _drawservice, IActivityTeam _activityteam, IWxConfigService _configService, IActivityTeamMembersService _activityteammembersservice, IActivityRuleService _activityruleservice) : base(s)
        {
            specialtopicservice = _specialtopicservice;
            categoryservice = _categoryservice;
            productservice = _productservice;
            spikeservice = _spikeservice;
            activityservice = _activityservice;
            drawservice = _drawservice;
            activityteam = _activityteam;
            configService = _configService;
            activityteammembersservice = _activityteammembersservice;
            activityruleservice = _activityruleservice;
        }
        #region 活动规则管理

        /// <summary>
        /// 规则列表页
        /// </summary>
        /// <returns></returns>
        public ActionResult ActivitRuleyList()
        {
            return View();
        }
        /// <summary>
        /// 列表数据
        /// </summary>
        /// <param name="search"></param>
        /// <returns></returns>
        public ActionResult GetActivitRuleyList(ActivityRuleSearchModel search)
        {
            int total = 0;
            var list = activityruleservice.GetActivityRuleList(search, ref total);
            return Json(new { Total = total, Results = list });
        }
        /// <summary>
        /// 规则详情页
        /// </summary>
        /// <returns></returns>
        public ActionResult ActivitRuleyEdit()
        {
            return View();
        }

        /// <summary>
        /// 初始化数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult ActivityRuleEdit(int id)
        {
            return Json(new { Result = activityruleservice.GetActivityRuleInfo(id) });
        }

        /// <summary>
        /// 新增或修改活动规则
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ActionResult SaveActivityRule(ActivityRule model)
        {
            Infrastructure.Result result = new Infrastructure.Result();


            if (model.ID > 0)
            {
                var entity = activityruleservice.GetActivityRuleInfo(model.ID);
                if (entity != null)
                {
                    entity.RuleContent = model.RuleContent;
                    if (activityruleservice.EditActivityRule(entity))
                    {
                        result.isSuccess = true;
                    }
                    else
                    {
                        result.msg = "更新失败";
                    }
                }
                else
                {
                    result.msg = "规则不存在";
                }
            }
            else
            {
                model.IsDeleted = false;
                if (activityruleservice.AddActivityRule(model) > 0)
                {
                    result.isSuccess = true;
                }
                else
                {
                    result.msg = "新增失败";
                }
            }
            return Json(result);
        }


        /// <summary>
        /// 删除规则
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult DelActivityRule(int id)
        {
            Infrastructure.Result result = new Infrastructure.Result();
            if (activityruleservice.DelActivityRule(id))
            {
                result.isSuccess = true;
                result.msg = "删除成功";
            }
            else
            {
                result.msg = "删除失败";
            }
            return Json(result);
        }

        #endregion
        #region 一分钱活动

        #region 活动列表
        /// <summary>
        /// 列表页面
        /// </summary>
        /// <returns></returns>
        [AuthorizeFilter(MenuRole = "51")]
        [HttpGet]
        // GET: Activity
        public ActionResult ActivityList()
        {
            return View();
        }

        /// <summary>
        /// 获取活动列表数据
        /// </summary>
        /// <param name="search"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult GetActivityList(ActivitySearchModel search)
        {
            int total = 0;
            var list = activityservice.GetActivityList(search, ref total);
            return Json(new { Total = total, Results = list });
        }



        /// <summary>
        /// 删除活动
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [AuthorizeFilter(MenuRole = "51")]
        [HttpPost]
        public ActionResult DelActivity(int id)
        {
            Infrastructure.Result result = new Infrastructure.Result();
            if (activityservice.DelActivity(id))
            {
                result.isSuccess = true;
                result.msg = "删除成功";
            }
            else
            {
                result.msg = "删除失败";
            }
            return Json(result);
        }

        /// <summary>
        /// 更新活动状态
        /// </summary>
        /// <param name="id"></param>
        /// <param name="activityStatus"></param>
        /// <returns></returns>
        [AuthorizeFilter(MenuRole = "51")]
        [HttpPost]
        public ActionResult UpdateActivityStatus(int id, int activityStatus)
        {
            Infrastructure.Result result = new Infrastructure.Result();
            if (activityservice.UpdateActivityStatus(id, activityStatus))
            {
                result.isSuccess = true;
                result.msg = "操作成功";
            }
            else
            {
                result.msg = "操作失败";
            }
            return Json(result);
        }

        /// <summary>
        /// 新增或修改活动
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ActionResult SaveActivity(Activity model)
        {
            Infrastructure.Result result = new Infrastructure.Result();
            if (!activityservice.CheckActivityName(model.Id, model.ActivityName))
            {
                result.msg = "活动名称已存在，请重新输入";
                return Json(result);
            }
            if (model.Id > 0)
            {
                var entity = activityservice.GetActivityInfo(model.Id);
                if (entity != null)
                {
                    entity.AddTime = DateTime.Now;
                    entity.ContinuedTime = model.ContinuedTime;
                    entity.CoverImg = model.CoverImg;
                    entity.IsDeleted = false;
                    entity.IsWinning = model.IsWinning;
                    entity.LuckDrawID = model.LuckDrawID;
                    entity.ParticipateNum = model.ParticipateNum;
                    entity.ActivityName = model.ActivityName;
                    entity.ActivityPrice = model.ActivityPrice;
                    entity.ActivityDetails = model.ActivityDetails;
                    entity.PeopleNum = model.PeopleNum;
                    entity.OpenTeamNum = model.OpenTeamNum;
                    entity.StartTime = model.StartTime;
                    entity.EndTime = model.EndTime;
                    entity.EditUserId = CurrentLoginUser.Id;
                    entity.EditTime = DateTime.Now;
                    if (activityservice.EditActivity(entity))
                    {
                        result.isSuccess = true;
                    }
                    else
                    {
                        result.msg = "更新失败";
                    }
                }
                else
                {
                    result.msg = "活动不存在";
                }
            }
            else
            {
                model.AddTime = DateTime.Now;
                model.ActivityStatus = 1;
                model.EditTime = DateTime.Now;
                if (activityservice.AddActivity(model) > 0)
                {
                    result.isSuccess = true;
                }
                else
                {
                    result.msg = "新增失败";
                }
            }
            return Json(result);
        }

        #endregion

        #region 活动列表编辑页面

        /// <summary>
        /// 编辑页面
        /// </summary>
        /// <returns></returns>
        [AuthorizeFilter(MenuRole = "51")]
        [HttpGet]
        // GET: Activity
        public ActionResult ActivityEdit()
        {
            return View();
        }

        /// <summary>
        /// 初始化数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [AuthorizeFilter(MenuRole = "51")]
        [HttpPost]
        public ActionResult ActivityEdit(int id)
        {
            return Json(new { Result = activityservice.GetVActivityInfo(id) });
        }
        #endregion
        #region 活动团



        #endregion

        #region 活动团成员



        #endregion

        #endregion


        /// <summary>
        /// 专题活动
        /// </summary>
        /// <returns></returns>
        [AuthorizeFilter(MenuRole = "51")]
        [HttpGet]
        // GET: Activity
        public ActionResult SpecialTopicManage()
        {
            return View();
        }

        /// <summary>
        /// 专题活动分页数据
        /// </summary>
        /// <param name="search"></param>
        /// <returns></returns>
        [AuthorizeFilter(MenuRole = "51")]
        [HttpPost]
        public ActionResult SpecialTopicManage(SpecialTopicSearchModel search)
        {
            int total = 0;
            var list = specialtopicservice.SpecialTopicManage(search, out total);
            return Json(new { Total = total, Results = list });
        }

        /// <summary>
        /// 新增、编辑专题活动
        /// </summary>
        /// <returns></returns>
        [AuthorizeFilter(MenuRole = "51")]
        [HttpGet]
        public ActionResult SpecialTopicEdit()
        {
            return View();
        }

        /// <summary>
        /// 初始化数据
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [AuthorizeFilter(MenuRole = "51")]
        [HttpPost]
        public ActionResult SpecialTopicEdit(int Id)
        {
            return Json(new { Result = specialtopicservice.SpecialTopicEdit(Id), CategoryList = categoryservice.GetCategoryList() });
        }

        /// <summary>
        /// 选择产品（销售中）
        /// </summary>
        /// <param name="search"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult ProductSelect(ProductSearchModel search)
        {
            int total = 0;
            var list = productservice.ProductSelect(search, out total);
            return Json(new { Total = total, Results = list });
        }

        /// <summary>
        /// 新增、编辑专题保存
        /// </summary>
        /// <param name="submitData"></param>
        /// <returns></returns>
        [AuthorizeFilter(MenuRole = "51")]
        [HttpPost]
        public ActionResult SpecialTopicEditSubmit(SpecialTopicResponse submitData)
        {
            return Json(specialtopicservice.SpecialTopicEditSubmit(submitData, CurrentLoginUser.Id));
        }

        /// <summary>
        /// 删除专题
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [AuthorizeFilter(MenuRole = "51")]
        [HttpPost]
        public ActionResult DelTopic(int Id)
        {
            return Json(specialtopicservice.DelTopic(Id, CurrentLoginUser.Id));
        }

        /// <summary>
        /// 秒杀活动管理
        /// </summary>
        /// <returns></returns>
        [AuthorizeFilter(MenuRole = "52")]
        [HttpGet]
        public ActionResult SpikeManage()
        {
            return View();
        }

        /// <summary>
        /// 秒杀活动分页数据
        /// </summary>
        /// <param name="search"></param>
        /// <returns></returns>
        [AuthorizeFilter(MenuRole = "52")]
        [HttpPost]
        public ActionResult SpikeManage(SpikeManageSearchModel search)
        {
            int total = 0;
            var list = spikeservice.SpikeManage(search, out total);
            return Json(new { Total = total, Results = list });
        }

        /// <summary>
        /// 删除秒杀活动
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [AuthorizeFilter(MenuRole = "52")]
        [HttpPost]
        public ActionResult DelSpike(int Id)
        {
            return Json(spikeservice.DelSpike(Id, CurrentLoginUser.Id));
        }

        /// <summary>
        /// 变更秒杀活动状态
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [AuthorizeFilter(MenuRole = "52")]
        [HttpPost]
        public ActionResult ChangeSpikeState(int Id)
        {
            return Json(spikeservice.ChangeSpikeState(Id, CurrentLoginUser.Id));
        }

        /// <summary>
        /// 活动延时
        /// </summary>
        /// <param name="EndTime"></param>
        /// <param name="Id"></param>
        /// <returns></returns>
        [AuthorizeFilter(MenuRole = "52")]
        [HttpPost]
        public ActionResult ChangeSpikeEndTime(DateTime EndTime, int Id)
        {
            return Json(spikeservice.ChangeSpikeEndTime(Id, EndTime, CurrentLoginUser.Id));
        }


        [HttpGet]
        public ActionResult SpikeEdit()
        {
            return View();
        }


        [HttpPost]
        public ActionResult SpikeEdit(int Id)
        {
            var result = spikeservice.SpikeEdit(Id);
            return Json(new { Activity = result.Activity, SpikeActivityInfoList = result.SpikeActivityInfoList, CategoryList = categoryservice.GetCategoryList() });
        }


        [HttpPost]
        public ActionResult SpikeEditSubmit(Activity_Spike Activity, List<Activity_SpikeSpec> SpikeActivityProductSelectedList)
        {
            return Json(spikeservice.SpikeEditSubmit(Activity, SpikeActivityProductSelectedList, CurrentLoginUser.Id));
        }


        /// <summary>
        /// 获取所有抽奖
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public JsonResult GetDrawListAll()
        {
            Infrastructure.Result result = new Infrastructure.Result();
            var list = drawservice.GetDrawListAll();
            Draw pc = new Draw();
            pc.Id = 0;
            pc.DrawName = "请选择";
            list.Insert(0, pc);
            result.data = list;


            return Json(result);
        }

        /// <summary>
        ///一分钱活动团页面
        /// </summary>
        /// <param name="activityid"></param>
        /// <returns></returns>
        public ActionResult ActivityTeamList()
        {
            return View();
        }

        [HttpPost]
        public ActionResult GetActivityTeamList(ActivitySearchModel search)
        {
            int total = 0;
            var list = activityteam.GetActivityTeamList(search, ref total);
            return Json(new { Total = total, Results = list });
        }

        /// <summary>
        ///一分钱活动团成员页面
        /// </summary>
        /// <param name="activityid"></param>
        /// <returns></returns>
        public ActionResult ActivityTeamMembersList()
        {
            return View();
        }

        [HttpPost]
        public ActionResult GetActivityTeamMembersList(ActivitySearchModel search)
        {
            int total = 0;
            var list = activityteam.GetActivityTeamMembersList(search, ref total);
            return Json(new { Total = total, Results = list });
        }

        /// <summary>
        /// 退款
        /// </summary>
        /// <param name="search"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult PayRefund(int Id)
        {
            Infrastructure.Result result = new Infrastructure.Result();

            int total = 0;
            var list = activityteam.GetActivityTeamInfo(Id, ref total);
            if (list != null)
            {
                //判断是否组团失败才退款
                if (list.TeamStatus == 1 && DateTime.Now > list.EndTime)
                {
                    var ActivityTeamMembers = list.ActivityTeamMembers;
                    bool isc = true;
                    string return_codedes = "";
                    foreach (ActivityTeamMembers item in ActivityTeamMembers)
                    {
                        if (item.RefundStatus == 2)
                        {

                          
                            bool wxsuccess = false;
                            string rt = Refund(item.OrderNo, item.OrderNo, (item.PaymentAmount * 100).ToString("0"), (item.PaymentAmount * 100).ToString("0"));


                            var res = XDocument.Parse(rt);

                            if (res != null && res.Element("xml") != null)
                            {
                                var return_code = res.Element("xml").Element("err_code");
                               
                                if (return_code == null)
                                {
                                    wxsuccess = true;
                                }
                                else
                                {
                                    return_codedes = res.Element("xml").Element("err_code_des").Value;
                                }
                            }

                            if (wxsuccess)
                            {
                                item.RefundStatus = 1;
                                activityteammembersservice.EditActivityTeamMembers(item);
                            }
                            else
                            {
                                isc = false;
                            }
                        }
                    }
                    if (isc)
                    {
                        list.TeamStatus = 4;
                        activityteam.EditActivityTeam(list);
                        result.isSuccess = true;
                        result.msg = "操作成功";
                    }
                    else
                    {
                        result.isSuccess = false;
                        result.msg = return_codedes;
                    }
                }
            }
            return Json(result);
        }

        /// <summary>
        /// 退款申请接口
        /// </summary>
        /// <param name="out_trade_no">填入商家订单号</param>
        /// <param name="out_refund_no">填入退款订单号</param>
        /// <param name="total_fee">填入总金额</param>
        /// <param name="refund_fee">填入退款金额</param>
        /// <returns></returns>
        public string Refund(string out_trade_no, string out_refund_no, string total_fee, string refund_fee)
        {
            //string appId = ConfigurationManager.AppSettings["AppId"];
            //string key = ConfigurationManager.AppSettings["Key"];
            //string mchId = ConfigurationManager.AppSettings["MchId"];

            var config = configService.GetConfig();

            string appId = config.AppId;
            string key = config.PaySignKey;
            string mchId = config.PartnerID;
            string certUrl = Server.MapPath("/cert/apiclient_cert.p12");
            string nonceStr = Senparc.Weixin.MP.TenPayLibV3.TenPayV3Util.GetNoncestr();
            Senparc.Weixin.MP.TenPayLibV3.RequestHandler packageReqHandler = new Senparc.Weixin.MP.TenPayLibV3.RequestHandler(null);

            //设置package订单参数
            packageReqHandler.SetParameter("appid", appId); //公众账号ID
            packageReqHandler.SetParameter("mch_id", mchId); //商户号
            packageReqHandler.SetParameter("out_trade_no", out_trade_no); //填入商家订单号
            packageReqHandler.SetParameter("out_refund_no", out_refund_no); //填入退款订单号
            packageReqHandler.SetParameter("total_fee", total_fee); //填入总金额
            packageReqHandler.SetParameter("refund_fee", refund_fee); //填入退款金额
            packageReqHandler.SetParameter("op_user_id", mchId); //操作员Id，默认就是商户号
            packageReqHandler.SetParameter("nonce_str", nonceStr); //随机字符串
            string sign = packageReqHandler.CreateMd5Sign("key", key);
            packageReqHandler.SetParameter("sign", sign); //签名
            //退款需要post的数据
            string data = packageReqHandler.ParseXML();

            //退款接口地址
            string url = "https://api.mch.weixin.qq.com/secapi/pay/refund";
            //本地或者服务器的证书位置（证书在微信支付申请成功发来的通知邮件中）
            string cert = certUrl;
            //私钥（在安装证书时设置）
            string password = mchId;
            ServicePointManager.ServerCertificateValidationCallback =
                new RemoteCertificateValidationCallback(CheckValidationResult);
            //调用证书
            X509Certificate2 cer = new X509Certificate2(cert, password,
                X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.MachineKeySet);

            #region 发起post请求

            HttpWebRequest webrequest = (HttpWebRequest)HttpWebRequest.Create(url);
            webrequest.ClientCertificates.Add(cer);
            webrequest.Method = "post";

            byte[] postdatabyte = Encoding.UTF8.GetBytes(data);
            webrequest.ContentLength = postdatabyte.Length;
            Stream stream;
            stream = webrequest.GetRequestStream();
            stream.Write(postdatabyte, 0, postdatabyte.Length);
            stream.Close();

            HttpWebResponse httpWebResponse = (HttpWebResponse)webrequest.GetResponse();
            StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream());
            string responseContent = streamReader.ReadToEnd();

            #endregion

            var res = XDocument.Parse(responseContent);
            return responseContent;
        }
        private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            if (errors == SslPolicyErrors.None)
                return true;
            return false;
        }


    }
}